<template>
  <div id="body" class="">
    <div class="content">
      <SPanel title="属性">
        <PropertyIndex></PropertyIndex>
      </SPanel>
      <div class="scene-header">
        <SPanel title="场景" :show-title="false" class="flex1">
          <div class="scene-content">
            <STab v-model:data="tabs"
                  @select="onSelectTab"
                  @close="onCloseTab"
                  ref="tabEl">
            </STab>
            <Subscribe v-show="showHome"></Subscribe>
            <SScene v-show="showScene" class="flex1"></SScene>
            <EventSheet v-for="(item, idx) in sheets"
                        :id="getSheetID(item.id)"
                        v-show="item.selected"
                        :key="idx">
            </EventSheet>
          </div>
        </SPanel>
      </div>
      <SPanel title="项目管理">
        <SAsset></SAsset>
      </SPanel>
      <div class="panel"
           draggable="false"
           v-if="false"
           ref="panel"
           @mousemove.capture="onPanelMouseMove"
           @mouseenter="onPanelMouseEnter"
           @mouseleave="onPanelMouseLeave"
           @mousedown="onPanelMouseDown"
      >
        <div class="toolBtn" @mousedown.stop="onMouseDown">
          <div class="flex1">窗口</div>
          <button @mousedown.stop="">最小</button>
          <button @mousedown.stop="">最大</button>
        </div>
      </div>
    </div>
    <SPanel title="控制台" v-if="false">

    </SPanel>
  </div>
</template>

<script lang="ts">
import { Rect } from './rect';
import { computed, defineComponent, nextTick, onMounted, ref, toRaw } from 'vue';
import SPanel from '@/ui-kit/panel/panel.vue';
import SAsset from './asset/index.vue';
import SScene from './scene/scene.vue';
import STab from '@/ui-kit/tabs/tabs.vue';
import PropertyIndex from './property/index.vue';
import EventSheet from './event/index.vue';
import { TabItem } from '@/ui-kit/tabs';
import { Emitter } from '@/ui-kit/index';
import Subscribe from './subscribe.vue';
import assetsStore from './store/assets';
import { AssetType, IAssetInfo } from './store/types';
import { Msg } from './msg';

const subscribe = 'subscribe';
export default defineComponent({
  name: 'editor-body',
  components: { Subscribe, PropertyIndex, STab, SScene, SPanel, SAsset, EventSheet },
  setup() {
    const panel = ref();
    const tabs = ref<TabItem[]>([]);
    tabs.value.push({ id: subscribe, name: '首页', canClose: false });
    const tabEl = ref<any>(null);

    function clickTableItem(id: string) {
      nextTick(() => {
        if (tabEl.value) {
          tabEl.value.onClickTabItem(id);
        }
      });
    }

    function selectLatest() {
      const len = tabs.value.length;
      if (len > 0) {
        clickTableItem(tabs.value[len - 1].id);
      } else {
        Emitter.emit(Msg.ShowAssetProperty, null);
      }
    }

    selectLatest();

    function autoSelectWhenDelAsset(data: IAssetInfo) {
      const idx = tabs.value.findIndex(el => el.id === data.id);
      if (idx !== -1) {
        const ret = tabs.value.splice(idx, 1)[0];
        if (ret.selected) {
          selectLatest();
        }
      }
    }

    onMounted(() => {
      Emitter.on(Msg.OpenAsset, (data: IAssetInfo) => {
        let item: TabItem | null = tabs.value.find(el => el.id === data.id) || null;
        if (!item) {
          item = {
            id: data.id, name: data.name,
          };
          tabs.value.push(item);
        }
        clickTableItem(data.id);
      });
      Emitter.on(Msg.AssetRename, (id: string) => {
        const ret = tabs.value.find(el => el.id === id);
        const asset = assetsStore().getAsset(id);
        if (ret && asset) {
          ret.name = toRaw(asset).name;
        }
      });
      Emitter.on(Msg.RemoveSceneAsset, (data: IAssetInfo) => {
        autoSelectWhenDelAsset(data);
      });
      Emitter.on(Msg.RemoveEventAsset, (data: IAssetInfo) => {
        // 检查删除的资源是否在tabs里面
        autoSelectWhenDelAsset(data);
      });
    });
    const showScene = ref(false);
    const showEvent = ref(false);
    const showHome = ref(false);
    const sheets = computed<TabItem[]>(() => {
      const ret: TabItem[] = [];
      tabs.value.forEach((tab: TabItem) => {
        const events = assetsStore().filterAssetByType(AssetType.Event);
        if (events.find(el => el.id === tab.id)) {
          ret.push(tab);
        }
      });
      return ret;
    });

    function resetShow() {
      showScene.value = false;
      showEvent.value = false;
      showHome.value = false;
    }

    return {
      sheets,
      tabEl,
      showScene,
      showEvent,
      showHome,
      panel,
      tabs,
      msg: ref('222'),
      onPanelMouseEnter() {
        // document.body.style.cursor = 'pointer'
      },
      onCloseTab(data: TabItem) {
        // 打开最新的
        Emitter.emit(Msg.CloseAsset, data.id);
        selectLatest();
      },
      onSelectTab(data: TabItem) {
        resetShow();
        if (data.id === subscribe) {
          showHome.value = true;
          Emitter.emit(Msg.ShowAssetProperty, null);
        } else {
          const asset: IAssetInfo | null = assetsStore().getAsset(data.id || '');
          if (asset) {
            Emitter.emit(Msg.ShowAssetProperty, asset);
            if (asset.type === AssetType.Object) {
            } else if (asset.type === AssetType.Scene) {
              showScene.value = true;
              Emitter.emit(Msg.RenderScene, asset);
            } else if (asset.type === AssetType.Event) {
              showEvent.value = true;
            }
          }
        }
      },
      onPanelMouseLeave() {
        document.body.style.cursor = 'default';
      },

      onPanelMouseDown() {
        console.log('panel');
      },
      getSheetID(id: string) {
        const ret = assetsStore().getAsset(id);
        if (ret && ret.type === AssetType.Event) {
          return ret.data;
        }
        return null;
      },
      onPanelMouseMove(event: MouseEvent) {
        const element: HTMLElement = panel.value as HTMLElement;
        const border = 5;
        const x = event.clientX;
        const y = event.clientY;
        let rect = new Rect(element.offsetLeft, element.offsetTop, element.offsetWidth, element.offsetHeight);
        if (rect.contain(x, y)) {
          document.body.style.cursor = 'pointer';
        }
        let leftTop = new Rect(rect.x, rect.y, border, border);
      },

      onMouseDown(event: MouseEvent) {
        let target: HTMLElement = panel.value as HTMLElement;
        let left = target.offsetLeft;
        let top = target.offsetTop;
        let clickX = event.clientX;
        let clickY = event.clientY;

        function mousemove(e: MouseEvent) {
          let diffX = e.clientX - clickX;
          let diffY = e.clientY - clickY;

          let parentWidth = document.body.clientWidth;
          let parentHeight = document.body.clientHeight;
          if (target.offsetParent) {
            parentHeight = target.offsetParent.clientHeight;
            parentWidth = target.offsetParent.clientWidth;
          }
          let newLeft = left + diffX;

          let maxLeft = parentWidth - target.offsetWidth;
          if (newLeft <= 0) {
            newLeft = 0;
          } else if (newLeft > maxLeft) {
            newLeft = maxLeft;
          }
          target.style.left = `${newLeft}px`;

          let newTop = top + diffY;
          let maxTop = parentHeight - target.offsetHeight;
          if (newTop <= 0) {
            newTop = 0;
          } else if (newTop >= maxTop) {
            newTop = maxTop;
          }
          target.style.top = `${newTop}px`;
        }

        function mouseup() {
          document.removeEventListener('mousemove', mousemove);
          document.removeEventListener('mouseup', mouseup);
        }

        document.addEventListener('mousemove', mousemove);
        document.addEventListener('mouseup', mouseup);
      },

      onMouseMove() {
      },
    };
  },
});
</script>

<style scoped lang="scss">
#body {
  position: relative;
  border: 1px solid black;
  display: flex;
  flex-direction: column;
  overflow: hidden;

  .flex1 {
    flex: 1;
  }

  .content {
    overflow: hidden;
    display: flex;
    flex: 1;
    flex-direction: row;

    .scene-header {
      display: flex;
      flex-direction: column;
      flex: 1;
      overflow: hidden;

      .scene-content {
        display: flex;
        flex-direction: column;
        width: 100%;
        height: 100%;
        overflow: hidden;
      }
    }
  }

  .panel {
    position: absolute;
    left: 0;
    top: 0;
    width: 400px;
    height: 400px;
    background-color: #2b85e4;

    .toolBtn {
      display: flex;
      flex-direction: row;
    }
  }
}

.vue-grid-layout {
  background: #eee;
}

.vue-grid-item:not(.vue-grid-placeholder) {
  background: #ccc;
  border: 1px solid black;
}

.vue-grid-item .resizing {
  opacity: 0.9;
}

.vue-grid-item .static {
  background: #cce;
}

.vue-grid-item .text {
  font-size: 24px;
  text-align: center;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  margin: auto;
  height: 100%;
  width: 100%;
}

.vue-grid-item .no-drag {
  height: 100%;
  width: 100%;
}

.vue-grid-item .minMax {
  font-size: 12px;
}

.vue-grid-item .add {
  cursor: pointer;
}

.vue-draggable-handle {
  position: absolute;
  width: 20px;
  height: 20px;
  top: 0;
  left: 0;
  background: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='10' height='10'><circle cx='5' cy='5' r='5' fill='#999999'/></svg>") no-repeat;
  background-position: bottom right;
  padding: 0 8px 8px 0;
  background-repeat: no-repeat;
  background-origin: content-box;
  box-sizing: border-box;
  cursor: pointer;
}
</style>
